package com.wms.security;

import com.alibaba.druid.support.json.JSONUtils;
import com.alibaba.fastjson.JSONObject;
import com.wms.controller.admin.BaseController;
import com.wms.entity.Admin;
import com.wms.plugin.JwtPlugin;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.stream.Collectors;

@Component
public class MyAuthenticationSuccessHandler implements AuthenticationSuccessHandler {

    private long expireMillis = 18000000;
    private String tokenPrefix = "Bearer ";
    private String tokenHeader = "Authorization";

    @Autowired
    private JwtPlugin jwtPlugin;

    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException {
        Admin admin = (Admin) authentication.getPrincipal();

        JSONObject subject = new JSONObject();
        subject.put("authorities", admin.getAuthorities().stream().map(e -> (((GrantedAuthority) e).getAuthority())).collect(Collectors.toList()));

        String token = jwtPlugin.createJWT(admin.getUsername(), subject.toJSONString(), expireMillis);

        JSONObject data = new JSONObject();
        data.put("token", token);
        data.put("username", admin.getUsername());

        response.setCharacterEncoding("utf-8");
        response.setContentType("application/json;utf-8");
        response.setHeader(tokenHeader, tokenPrefix + token);
        response.getWriter().write(JSONUtils.toJSONString(BaseController.success(data)));
    }


}
